<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\admin\validate\ArticlesValidate;
use think\facade\View;
use app\admin\model\Articles;
use think\Response;

class ArticlesController extends Base
{
    /**
     * 文章列表
     *
     * @return string|\think\response\Json
     */
    public function index(Articles $articles)
    {
        if (request()->isAjax()) {

            $param = request()->param();
            $limit = $param['pageSize'];

            $where = [];
            if (!empty($param['searchText'])) {
                $where[] = ['title', 'like', "%{$param['searchText']}%"];
            }

            $selectResult = $articles->getArticlesByWhere((array)$where, (int)$limit);

            $selectResult->each(function ($value) {
                $value->thumbnail = '<img alt="image" src="' . getImgUrl($value['thumbnail'], app('http')->getName()) . '" width="40px" height="40px">';
                $value->operate   = showOperate($this->makeButton($value['id']));
            });

            $return['total'] = $selectResult->total();  // 总数据
            $return['rows']  = $selectResult->all();

            return json($return);
        }

        return View::fetch();

    }

    /**
     * 添加页面
     *
     * @param Articles $articles
     * @param ArticlesValidate $articlesValidate
     * @return Response|string
     */
    public function Add(Articles $articles, ArticlesValidate $articlesValidate): string
    {

        if (request()->isAjax()) {
            $param = \request()->param();

            unset($param['file']);

            $isValid = $articlesValidate->check($param);
            if (!$isValid) {
                $this->error($articlesValidate->getError());
            }

            $flag = $articles->save($param);

            if ($flag) {
                $this->success('添加成功', (string)url('articles/index'));
            } else {
                $this->error('添加失败');
            }
        }

        return View::fetch();
    }

    /**
     * 上传图片
     *
     * @return Response
     */
    public function uploadImg(): Response
    {

        if (\request()->isAjax()) {
            $file = \request()->file('file');
            // 上传到本地服务器
            $savename  = \think\facade\Filesystem::disk('public')->putFile('', $file);
            $file_name = $file->hashName();
            $this->success('上传成功', '', ['src' => $file_name, 'url' => getImgUrl($file_name, app('http')->getName())]);
        }

        $this->error('失败');

    }

    /**
     * 修改文章
     *
     * @param int $id
     * @param Articles $articles
     * @param ArticlesValidate $articlesValidate
     * @return Response|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit(int $id, Articles $articles, ArticlesValidate $articlesValidate): string
    {

        $article = $articles::find($id);

        if (\request()->isAjax()) {
            $param = \request()->param();
            unset($param['file']);
            $param['add_time'] = date('Y-m-d H:i:s');

            $isValid = $articlesValidate->check($param);
            if (!$isValid) {
                $this->error($articlesValidate->getError());
            }

            $flag = $articles->update($param);

            if ($flag) {
                $this->success('修改成功', (string)url('articles/index'));
            } else {
                $this->error('修改失败');
            }
        }


        $article->thumbnails = getImgUrl($article->thumbnail, app('http')->getName());
        View::assign('article', $article);
        return View::fetch();

    }

    /**
     * 删除文章
     *
     * @param int $id
     * @param Articles $articles
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function delete(int $id, Articles $articles): Response
    {
        $article = $articles::find($id) ?? (object)[];

        if ($article) {
            $article->delete();
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    /**
     * 拼装操作按钮
     * @param $id
     * @return array
     */
    private function makeButton(int $id): array
    {
        return [
            '编辑' => [
                'auth'     => 'articles/edit',
                'href'     => url('articles/edit', ['id' => $id]),
                'btnStyle' => 'primary',
                'icon'     => 'fa fa-paste'
            ],
            '删除' => [
                'auth'     => 'articles/delete',
                'href'     => "javascript:articleDel('{$id}')",
                'btnStyle' => 'danger',
                'icon'     => 'fa fa-trash-o'
            ]
        ];
    }
}
